package com.haitai.solr.controller;

import com.alibaba.fastjson.JSONObject;
import com.haitai.solr.resp.Pager;
import com.haitai.solr.resp.RespData;
import com.haitai.solr.resp.StateCodeDesc;
import com.haitai.solr.utils.SolrOprUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.solr.common.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Base64;
import java.util.TreeMap;
import java.util.UUID;

@RestController
@RequestMapping("/solr/operation")
@Api(value="springboot与solr整合",tags = "springboot与solr整合")
public class HttpSolrOprController {

    private Logger logger = LoggerFactory.getLogger(HttpSolrOprController.class);

    @Value("${solr.url}")
    private String solrUrl;


    @PostMapping(value = "/addInfo")
    @ApiOperation(value="添加数据",notes="添加数据",response=String.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "coreName", value = "solr服务名", required = true, dataType = "String"),
            @ApiImplicitParam(name = "reqJson", value = "reqJson是base64编码后的json字符串", required = false, dataType = "String")
    })
    public RespData<Object> addInfomation(@RequestParam(value="coreName",defaultValue="fileStorage") String coreName,
                                          @RequestParam(value="reqJson",defaultValue="") String reqJson) {

        TreeMap<String, Object> map = null;
        try {
            reqJson = new String(Base64.getDecoder().decode(reqJson.getBytes("UTF-8")));
            map = JSONObject.parseObject(reqJson, TreeMap.class);
        } catch (Exception e) {
            logger.error("reqJson不是json字符串", e);
            return RespData.failRsp(StateCodeDesc.PARAM_ERROR.getCode(), "reqJson参数有误");
        }

        if (map.isEmpty()) {
            return RespData.failRsp(StateCodeDesc.PARAM_ERROR.getCode(), StateCodeDesc.PARAM_ERROR.getCodeDesc());
        }

        map.put("id", UUID.randomUUID().toString());
        String addUrl = solrUrl + "/" + coreName;
        boolean addFlag = SolrOprUtils.addInfoToSolr(addUrl, map);
        if (!addFlag) {
            return RespData.failRsp("9002", "添加失败");
        }
        return RespData.successRsp(true);
    }

    @PostMapping(value = "/updateInfo")
    @ApiOperation(value="更新数据",notes="更新数据,json中数据要有需要更新的id值",response=String.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "coreName", value = "solr服务名", required = true, dataType = "String"),
            @ApiImplicitParam(name = "reqJson", value = "reqJson是base64编码后的json字符串,json中数据要有需要更新的id值", required = false, dataType = "String")
    })
    public RespData<Object> updateInfomation(@RequestParam(value="coreName",defaultValue="fileStorage") String coreName,
                                          @RequestParam(value="reqJson",defaultValue="") String reqJson) {

        TreeMap<String, Object> map = null;
        try {
            reqJson = new String(Base64.getDecoder().decode(reqJson.getBytes("UTF-8")));
            map = JSONObject.parseObject(reqJson, TreeMap.class);
        } catch (Exception e) {
            logger.error("reqJson不是json字符串", e);
            return RespData.failRsp(StateCodeDesc.PARAM_ERROR.getCode(), "reqJson参数有误");
        }

        if (map.isEmpty()) {
            return RespData.failRsp(StateCodeDesc.PARAM_ERROR.getCode(), StateCodeDesc.PARAM_ERROR.getCodeDesc());
        }

        String addUrl = solrUrl + "/" + coreName;
        boolean addFlag = SolrOprUtils.updateInfoToSolr(addUrl, map);
        if (!addFlag) {
            return RespData.failRsp("9002", "更新失败");
        }
        return RespData.successRsp(true);
    }


    @PostMapping(value = "/delInfo")
    @ApiOperation(value="删除数据",notes="删除数据,根据key/value删除数据",response=String.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "coreName", value = "solr服务名", required = true, dataType = "String"),
            @ApiImplicitParam(name = "allocatedKey", value = "solr中分配的key", required = true, dataType = "String"),
            @ApiImplicitParam(name = "allocatedValue", value = "solr中分配的value", required = false, dataType = "String")
    })
    public RespData<Object> delInfo(@RequestParam(value="coreName",defaultValue="fileStorage") String coreName,
                                    @RequestParam(value="allocatedKey",defaultValue="") String allocatedKey,
                                    @RequestParam(value="allocatedValue",defaultValue="") String allocatedValue) {
        String delUrl = solrUrl + "/" + coreName;
        boolean addFlag = SolrOprUtils.delByParam(delUrl, allocatedKey, allocatedValue);
        if (!addFlag) {
            return RespData.failRsp("9002", "删除失败");
        }
        return RespData.successRsp(true);
    }

    @PostMapping(value = "/queryInfo")
    @ApiOperation(value="查询数据",notes="查询数据,分页查询",response=String.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "coreName", value = "solr服务名", required = true, dataType = "String"),
            @ApiImplicitParam(name = "queryData", value = "查询条件，需要自己组装solr的条件，需要base64数据 类似 id:* and content:人民币", required = true, dataType = "String"),
            @ApiImplicitParam(name = "start", value = "分页的起始页", required = false, dataType = "Integer"),
            @ApiImplicitParam(name = "rows", value = "每页显示的数量", required = false, dataType = "Integer")
    })
    public RespData<Object> queryInfo(@RequestParam(value="coreName",defaultValue="fileStorage") String coreName,
                                      @RequestParam(value="queryData",defaultValue="") String queryData,
                                      @RequestParam(value="start",defaultValue="1") Integer start,
                                      @RequestParam(value="rows",defaultValue="10") Integer rows) {
        try {
            queryData = new String(Base64.getDecoder().decode(queryData.getBytes("UTF-8")));
        } catch (Exception e) {
            logger.error("queryData参数传入解码异常", e);
            return RespData.failRsp(StateCodeDesc.PARAM_ERROR.getCode(), "queryData参数有误");
        }

        Pager pager = new Pager();
        if (start == null) {
            pager.setCurrentPage(1);
        } else {
            pager.setCurrentPage(start);
        }

        if (rows != null) {
            pager.setPageSize(rows);
        } else {
            pager.setPageSize(10);
        }
        String queryUrl = solrUrl + "/" + coreName;
        // 返回字段，需要在solr服务器的schema设置相关字段，否则不能使用
        String outputItem = "id,fileguid,dfilename,filepath,createtime,mj,dfiletype,fepguid,subid,dfilecontext";
        pager = SolrOprUtils.queryPageData(queryUrl, queryData, outputItem, pager);
        return RespData.successRsp(pager);
    }

}
